import 'package:dynamic_stock/const/const.dart';
import 'package:flutter/material.dart';
import 'dart:math';


class PieChartWidget extends StatefulWidget {

  final double size;
  final List<Color> listColor;
  final List<double> listVal;

  String userPercent = "0"; // 用户的占股比列

   PieChartWidget({Key key, @required this.size, @required this.listColor, @required this.listVal}) : super(key: key){
     if(listVal != null && listVal.length > 0){
      userPercent = (listVal.first * 100).toStringAsFixed(2);
     }
   }

  @override
  _PieChartWidgetState createState() => _PieChartWidgetState();
}

class _PieChartWidgetState extends State<PieChartWidget> with SingleTickerProviderStateMixin {

  Animation<double> _animation;
  AnimationController _animationController;
  
  final double normalStroke = 15;
  final double activeStroke = 25;

  @override
  initState(){
    super.initState();

    _animationController = AnimationController(duration: Duration(milliseconds: 1000));
    CurvedAnimation curve = CurvedAnimation(curve: Curves.bounceInOut, parent: _animationController);
    double sum = widget.listVal.reduce((obj1,obj2){
      return obj1 + obj2;
    });
    _animation = Tween<double>(begin: 0, end: sum).animate(curve)
      ..addListener((){
        setState(() {
          
        });
      });

      _animationController.forward();
  }

  @override
  dispose(){
    _animationController.dispose();
    super.dispose();
  }

  Paint _createPainter(double strokeWidth, Color color) {
    return Paint()
          ..color = color
          ..strokeWidth = strokeWidth
          ..style = PaintingStyle.stroke
          ..isAntiAlias = true;
  }

  List<Widget> _createPaint(){

    List<Widget> res = [
      CustomPaint(painter: PieChartPainter(_createPainter(normalStroke , Color(0xffF3F0FB)), widget.size)) // 初始化底部的圆
    ];

    // 添加弧线
    double val = 0;
    double end = -pi / 2;
    for(int i=0;i<widget.listColor.length;i++){
      val = (2 * pi) * widget.listVal[i] * _animation.value;
      CustomPaint r = CustomPaint(
        painter: PieChartPainter2(_createPainter(i == 0 ? activeStroke : normalStroke , widget.listColor[i]), widget.size, end, val)
      );
      end += val;
      res.add(r);
    }

    // 添加中心的文字
    res.add(_createCenter());
    return res;
  }

  Widget _createCenter(){
    return Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RichText(
                text: TextSpan(
                  children: [
                    TextSpan(text: "${widget.userPercent}", style: TextStyle(color: Color(0xff5F5D70), fontSize: 60, fontWeight: FontWeight.w500)),
                    TextSpan(text: " %", style: TextStyle(color: Color(0xff5F5D70), fontSize: 24))
                  ]
                ),
            ),
            Container(
              child: Text("动态股份"),
            )
          ],
        ),
      );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        alignment: Alignment.topCenter,
        children: _createPaint(),
      ),
    );
  }
}

class PieChartPainter extends CustomPainter {

  final double csize;
  final Paint  painter;

  PieChartPainter(this.painter, this.csize);

  @override
  void paint(Canvas canvas, Size size) {
    double offsetH = csize;
    canvas.drawCircle(Offset(0, offsetH), csize, painter);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return false;
  }
}

class PieChartPainter2 extends CustomPainter {

  final double csize;
  final Paint  painter;
  final double begin;
  final double val;

  PieChartPainter2(this.painter, this.csize, this.begin, this.val);

  @override
  void paint(Canvas canvas, Size size) {
    double offsetH = csize;
    var rect = Rect.fromCircle(center: Offset(0, offsetH), radius: csize);
    canvas.drawArc(rect, begin,  val, false, painter);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}